package com.zscat.mallplus.utils;

import com.zscat.mallplus.dms.vo.DriverOrderParam;
import com.zscat.mallplus.qsg.QsgStore;
import org.apache.commons.lang.StringUtils;

import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;

public class BusinessUtil {

    /**
     * 检查订单的开始时间和结束时间是否都在营业时间内（支持跨天的营业时间和订单时间）
     *
     * @param orderStart 订单开始时间
     * @param orderEnd 订单结束时间
     * @return 如果订单的开始时间和结束时间都在营业时间内，则返回 true；否则返回 false
     */
    public static boolean isOrderWithinBusinessHours(LocalTime orderStart, LocalTime orderEnd, QsgStore store) {
        if(StringUtils.isBlank(store.getStartTime()) || StringUtils.isBlank(store.getEndTime())){
            return true;
        }
        String startHour = StringUtils.split(store.getStartTime(),":")[0];
        String startMint = StringUtils.split(store.getStartTime(),":")[1];
        String endHour = StringUtils.split(store.getEndTime(),":")[0];
        String endMint = StringUtils.split(store.getEndTime(),":")[1];
        boolean isStartInBusinessHours = isTimeInBusinessHours(orderStart,LocalTime.of(Integer.parseInt(startHour),Integer.parseInt(startMint)),LocalTime.of(Integer.parseInt(endHour),Integer.parseInt(endMint)));
        boolean isEndInBusinessHours = isTimeInBusinessHours(orderEnd,LocalTime.of(Integer.parseInt(startHour),Integer.parseInt(startMint)),LocalTime.of(Integer.parseInt(endHour),Integer.parseInt(endMint)));
        return isStartInBusinessHours && isEndInBusinessHours;
    }

    /**
     * @param time 给定时间
     * @return 是否在营业时间内
     */
    private static boolean isTimeInBusinessHours(LocalTime time,LocalTime businessStart,LocalTime businessEnd) {
        // 判断营业时间是否跨天（结束时间小于开始时间）
        if (businessEnd.isBefore(businessStart)) {
            // 营业时间跨天
            return !time.isBefore(businessStart) || !time.isAfter(businessEnd);
        } else {
            // 营业时间不跨天
            return !time.isBefore(businessStart) && !time.isAfter(businessEnd);
        }
    }

    public static void main(String[] args) {
        DriverOrderParam orderParam = new DriverOrderParam();
        orderParam.setStartTime("2024/12/20 08:00");
        orderParam.setEndTime("2024/12/20 03:01");
        QsgStore store = new QsgStore();
        store.setStartTime("08:00");
        store.setEndTime("03:00");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(orderParam.getStartTime()));
        LocalTime start = LocalTime.of(calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE));
        calendar.setTime(new Date(orderParam.getEndTime()));
        LocalTime end = LocalTime.of(calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE));
        boolean res = BusinessUtil.isOrderWithinBusinessHours(start,end,store);
        System.out.println(res);
    }
}
